package com.activity;

import android.content.Context;
import android.content.Intent;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.pojo.User;
import com.tools.Constants;
import com.tools.LoginCandidate;
import com.tools.SomeMonitorEditText;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class LoginActivity extends AppCompatActivity {

    private ImageButton 后退按钮;
    private AutoCompleteTextView  编辑用户名;
    private EditText 编辑密码;
    private Button 登录按钮;
    private Button 注册;
    private CheckBox 记住密码;
    private TextView 忘记密码;



    //登录候选列表
    private ImageView 登录候选;
    List<String> autoUserName = new ArrayList<String>();
    boolean isOnClick = true;

    //记住密码
    SharedPreferences sp = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);


        后退按钮 = (ImageButton) findViewById(R.id.后退按钮);
        编辑用户名 = (AutoCompleteTextView) findViewById(R.id.编辑用户名);
        编辑密码 = (EditText) findViewById(R.id.编辑密码);
        登录按钮 = (Button) findViewById(R.id.登录按钮);
        注册 = (Button) findViewById(R.id.注册);
        记住密码 = (CheckBox) findViewById(R.id.记住密码);
        忘记密码 = (TextView) findViewById(R.id.忘记密码);
        登录候选 = (ImageView) findViewById(R.id.登录候选);

        new SomeMonitorEditText().SetMonitorEditText(登录按钮,编辑用户名,编辑密码);

        //获取本地登录候选
        LoginCandidate.getUserName(LoginActivity.this,autoUserName);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, autoUserName);
        编辑用户名.setAdapter(adapter);
        登录候选.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isOnClick == true){
                    编辑用户名.showDropDown();
                    isOnClick=false;
                }else {
                    编辑用户名.dismissDropDown();
                    isOnClick=true;
                }
            }
        });

        sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        if (sp.getBoolean("checkboxBoolean", false)){
            编辑用户名.setText(sp.getString("uname", null));
            编辑密码.setText(sp.getString("upswd", null));
            记住密码.setChecked(true);
        }


        后退按钮.setVisibility(View.INVISIBLE);
        后退按钮.setEnabled(false);

        注册.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, Register1Activity.class);
                startActivity(intent);
                LoginActivity.this.finish();
            }
        });

        忘记密码.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, ForgetPwd1Activity.class);
                startActivity(intent);
                LoginActivity.this.finish();
            }
        });

        登录按钮.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = 编辑用户名.getText().toString().trim();
                String pwd = 编辑密码.getText().toString().trim();
                String path = "http://101.200.40.47:8080/stu/user/doLogin?userName="+name+"&password="+pwd;
                new doLogin().execute(path);
            }
        });
    }

    //判断登录
    private class doLogin extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");//这个应该都知道是干嘛的，默认是GET  
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if(o==null){
                Toast.makeText(LoginActivity.this, "账号或密码输入错误！", Toast.LENGTH_SHORT).show();
                编辑用户名.setText(null);
                编辑密码.setText(null);
            }else{
                String info = o.toString().trim();
                try {
                    JSONObject jo = new JSONObject(info);

                    /*user.setUid(jo.getString("uid"));
                    user.setUserName(jo.getString("userName"));
                    user.setGender(jo.getString("gender"));
                    user.setPhone(jo.getString("phone"));
                    user.setUserCode(jo.getString("userCode"));
                    user.setUserHead(jo.getString("userHead"));
                    user.setCreationDate(jo.getString("creationDate"));*/

                    Constants.USER_ROOT.setUid(jo.getString("uid"));
                    Constants.USER_ROOT.setUserName(jo.getString("userName"));
                    Constants.USER_ROOT.setGender(jo.getString("gender"));
                    Constants.USER_ROOT.setPhone(jo.getString("phone"));
                    Constants.USER_ROOT.setUserCode(jo.getString("userCode"));
                    Constants.USER_ROOT.setUserHead(jo.getString("userHead"));
                    Constants.USER_ROOT.setCreationDate(jo.getString("creationDate"));

                    Toast.makeText(LoginActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();

                    LoginCandidate.saveUserName(LoginActivity.this,Constants.USER_ROOT.getUserName());//保存登录名

                    if(记住密码.isChecked()==true){
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("uname", 编辑用户名.getText().toString().trim());
                        editor.putString("upswd", 编辑密码.getText().toString().trim());
                        editor.putBoolean("checkboxBoolean", true);
                        editor.commit();
                    }else{
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("uname",null);
                        editor.putString("upswd",null);
                        editor.putBoolean("checkboxBoolean", false);
                        editor.commit();
                    }
                    if(Constants.USER_ROOT.getUserCode().equals("1")){
                        Intent intent = new Intent();
                        intent.setClass(LoginActivity.this, AdminActivity.class);
                        startActivity(intent);
                        LoginActivity.this.finish();
                    }else if(Constants.USER_ROOT.getUserCode().equals("2")){
                        Intent intent = new Intent();
                        intent.setClass(LoginActivity.this, UserActivity.class);
                        startActivity(intent);
                        LoginActivity.this.finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }

    long mExitTime;       //实现“再按一次退出”的记录时间变量
    @Override //再按一次退出程序
    public void onBackPressed() {
        if (System.currentTimeMillis() - mExitTime < 2000) {
            super.onBackPressed();
        } else {
            mExitTime = System.currentTimeMillis();
            Toast.makeText(LoginActivity.this,"再按一次退出应用",Toast.LENGTH_SHORT).show();
        }
    }

}




